from django.http import HttpResponse,JsonResponse
from django.shortcuts import render,redirect
from web.forms.wiki import WikiModelForm
from django.urls import reverse
from web import models

from django.views.decorators.csrf import csrf_exempt

from utils.encrypt import uid
from utils.tencent.cos import upload_file

def  wiki(request,project_id):
    """wiki首页展示"""
    wiki_id = request.GET.get('wiki_id')
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, 'wiki.html')

    wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()

    return render(request, 'wiki.html', {'wiki_object': wiki_object})

def wiki_add(request,project_id):
    """wiki添加文章"""
    if request.method == "GET":
        form = WikiModelForm(request)
        return render(request,'wiki_form.html',{'form':form})

    form = WikiModelForm(request,data=request.POST)
    
   
    if form.is_valid():
        # 判断用户是否已经选择了父文章
        print(form.instance.parent,type(form.instance.parent))
        if form.instance.parent:
            form.instance.depth = form.instance.depth + 1
        else:
            form.instance.depth = 1

        form.instance.project = request.saas.project
        form.save()
        url = reverse('web:wiki',kwargs={'project_id':project_id})
        return redirect(url)
    return render(request,'wiki_add.html',{'form':form})
    
def wiki_catalog(request,project_id):
    """多级目录"""
    
    # 获取当前项目所有目录:data = QuerySet类型
    '''
        values_list:返回给前端ajax:res.data的数据是列表形式:
        [1, "王允啊", null]
        [2, "科比", 1]
    '''
    # data = models.Wiki.objects.filter(project=request.saas.project).values_list('id','title','parent_id')
    '''
        values返回给前端ajax:res.data的数据是字典类型:
        {id: 1, title: "王允啊", parent_id: null}
        {id: 2, title: "科比", parent_id: 1}
    '''
    data = models.Wiki.objects.filter(project=request.saas.project).values('id','title','parent_id').order_by('depth','id')
    #data = models.Wiki.objects.filter(project=request.saas.project).values('id','title','parent_id')
   
    print(data)
    # json.dumps(QuerySet类型):无法进行序列化
    return JsonResponse({'status':True,'data':list(data)})

'''
文章预览功能
/detail?wiki_id=1
/detail?wiki_id=2
def wiki_detail(request,project_id):
    pass
'''

def wiki_delete(request,project_id,wiki_id):
    '''
        wiki删除
        理论上点删除应该弹出对话框，询问用户是否删除？此处省略
    '''
    models.Wiki.objects.filter(project_id=project_id, id=wiki_id).delete()

    url = reverse('web:wiki', kwargs={'project_id': project_id})
    return redirect(url)


def wiki_edit(request,project_id,wiki_id):
    '''wiki编辑'''
    wiki_object = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    if not wiki_object:
        url = reverse('wiki', kwargs={'project_id': project_id})
        return redirect(url)
    if request.method == "GET":
        form = WikiModelForm(request, instance=wiki_object)
        return render(request, 'wiki_form.html', {'form': form})

    form = WikiModelForm(request, data=request.POST, instance=wiki_object)
    if form.is_valid():
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.save()
        url = reverse('web:wiki', kwargs={'project_id': project_id})
        preview_url = "{0}?wiki_id={1}".format(url, wiki_id)
        return redirect(preview_url)

    return render(request, 'wiki_form.html', {'form': form})

@csrf_exempt
def wiki_upload(request, project_id):
    """ markdown插件上传图片 """
    result = {
        'success': 0,
        'message': None,
        'url': None
    }

    image_object = request.FILES.get('editormd-image-file')
    if not image_object:
        result['message'] = "文件不存在"
        return JsonResponse(result)

    ext = image_object.name.rsplit('.')[-1]
    key = "{}.{}".format(uid(request.saas.user.mobile_phone), ext)
    image_url = upload_file(
        request.saas.project.bucket,
        request.saas.project.region,
        image_object,
        key
    )
    result['success'] = 1
    result['url'] = image_url
    return JsonResponse(result)